package com.my.blog.website.task;

import com.my.blog.website.modal.Vo.LogVo;
import com.my.blog.website.service.ILogService;
import com.my.blog.website.service.IMailService;
import com.my.blog.website.utils.DateKit;
import com.sun.management.OperatingSystemMXBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.lang.management.ManagementFactory;
import java.util.Date;
import java.util.List;

/**
 * @Description 博客状态定时任务
 * @ClassName TaskEmail
 * @Author gyh
 * @date 2019.12.19 13:43
 */
@Component
public class TaskEmail {
    @Resource
    ILogService logService;

    @Resource
    IMailService mailService;

    @Value("${spring.mail.username}")
    private String mailTo;

    /***
     * 执行定时系统运行状态邮件
     * cron表达式 [秒]0-59 [分]0-59 [小时]0-23 [日]1-31 [月]1-12 / JAN-DEC  [周]1-7 or SUN-SAT [年]1970-2099（可省略）
     * fixedDelay：上一次执行完毕时间点之后多长时间再执行 fixedDelayString：字符串形式的fixedDelay
     * fixedRate：上一次开始执行时间点之后多长时间再执行 fixedRateString：字符串形式fixedRate
     * initialDelay：第一次延迟多长时间后再执行
     * @Scheduled(fixedRate = 86400000)
     */
    @Scheduled(cron = "0 0 9 * * 1,5")
    public void process() throws UnsupportedEncodingException {
        StringBuffer sb = new StringBuffer();
        //获取系统总内存（jvm从系统争夺的内存，若设置Xms=64M,是指这个数字，单位的字节）
        long totalMemory = Runtime.getRuntime().totalMemory();
        //获取系统空闲内存(获取的总内存，但是有时候会多获取到的这部分)
        long freeMemory = Runtime.getRuntime().freeMemory();
        sb.append("总内存为：" + totalMemory / (1024 * 1024) + "MB").append("\n");
        sb.append("空闲内存：" + freeMemory / (1024 * 1024) + "MB").append("\n");
        sb.append("内存使用率：" + getMemoryUsage()).append("\n");
        //获取最新五条日志
        List<LogVo> logs = logService.getLogs(0, 5);
        for (LogVo logVo : logs) {
            sb.append(" 时间: ").append(DateKit.formatDateByUnixTime(logVo.getCreated()));
            sb.append(" 操作: ").append(logVo.getAction());
            sb.append(" IP： ").append(logVo.getIp()).append("\n");
        }
        mailService.sendSimpleEmail(mailTo, "cnbs运行情况:", sb.toString());
    }

    /**
     * 计算内存使用率
     *
     * @return
     */
    public static String getMemoryUsage() {
        OperatingSystemMXBean osmxb = ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class);
        //获取总虚拟内存大小
        long totalvirtualMemory = osmxb.getTotalSwapSpaceSize();
        //获取空闲物理内存大小
        long freePhysicalMemorySize = osmxb.getFreePhysicalMemorySize();
        Double memPer = (1 - freePhysicalMemorySize * 1.0 / totalvirtualMemory) * 100;
        String s = memPer.intValue() + "%";
        return s;
    }

    public static void main(String[] args) {
        int z=0;
        for (int i = 0; i ==z ; i++) {
            z++;
        }
        System.out.println(z);

    }

}
